﻿Imports WiremetModel.Entities.SupplyOrders
Imports GMap.NET
Imports GMap.NET.WindowsForms
Imports InputValidation.GeneralRules
Imports InputValidation
Imports System.ComponentModel

Public Class SupplierInputDialog

    Private _id As Integer
    Private _supplier As Supplier
    Public Property Supplier() As Supplier
        Get
            Return _supplier
        End Get
        Private Set(ByVal value As Supplier)
            _supplier = value
        End Set
    End Property

    Private _supplierAddressList As List(Of SupplierAddress)
    Private _supplierLocationOverlay As GMapOverlay

    Private _inputValidator As InputValidator


    Public Sub New()
        InitializeComponent()
        _supplierAddressList = New List(Of SupplierAddress)
        InitializeSupplierAddressMap()
        ClearErrorLabels()
        _inputValidator = New InputValidator()
        Supplier = New Supplier()
    End Sub


    Public Sub New(ByVal supplier As Supplier)

        Me.New()

        _supplier = supplier
        tb_CompanyName.Text = supplier.CompanyName
        tb_EmailAddress.Text = supplier.EmailAddress
        tb_FaxNumber.Text = supplier.FaxNumber
        tb_TelephoneNumber.Text = supplier.TelephoneNumber

        _supplierAddressList = New List(Of SupplierAddress)(supplier.SupplierAddresses)
        RefreshSupplierAddressListBox(_supplierAddressList)

    End Sub

    Private Sub InitializeSupplierAddressMap()

        GMap_SupplierAddress.MapProvider = MapProviders.GoogleMapProvider.Instance
        GMaps.Instance.Mode = AccessMode.ServerAndCache
        GMap_SupplierAddress.ForceDoubleBuffer = True
        GMap_SupplierAddress.Zoom = 8
        _supplierLocationOverlay = New GMapOverlay(GMap_SupplierAddress, "supplierLocationOverlay")
        GMap_SupplierAddress.Overlays.Add(_supplierLocationOverlay)

    End Sub

    Private Sub ClearErrorLabels()

        lbl_CompanyNameError.Text = String.Empty
        lbl_TelephoneNumberError.Text = String.Empty
        lbl_EmailAddressError.Text = String.Empty

    End Sub

    Public Sub RefreshSupplierAddressListBox(ByVal supplierAddressList As IEnumerable(Of SupplierAddress))
        lb_SupplierAddress.DataSource = New BindingSource(_supplierAddressList, Nothing)
    End Sub


#Region "Supplier Address"

    Private Sub lb_SupplierAddress_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles lb_SupplierAddress.SelectedIndexChanged
        Dim supplierAddress As SupplierAddress = CType(lb_SupplierAddress.SelectedValue, SupplierAddress)
        If Not IsNothing(supplierAddress) Then
            tb_SelectedSupplierAddress.Text = supplierAddress.Address.ToString()
            Dim addressLocation As New PointLatLng(supplierAddress.Address.Latitude, supplierAddress.Address.Longitude)
            Dim marker As GMapMarker = New Markers.GMapMarkerGoogleRed(addressLocation)
            _supplierLocationOverlay.Markers.Clear()
            marker.ToolTipText = supplierAddress.Description & vbNewLine & supplierAddress.Address.ToString()
            marker.ToolTipMode = MarkerTooltipMode.Always
            _supplierLocationOverlay.Markers.Add(marker)
            GMap_SupplierAddress.ZoomAndCenterMarkers(_supplierLocationOverlay.Id)
            GMap_SupplierAddress.Zoom = 12
        Else
            tb_SelectedSupplierAddress.Text = String.Empty
            _supplierLocationOverlay.Markers.Clear()
            GMap_SupplierAddress.ZoomAndCenterMarkers(_supplierLocationOverlay.Id)
            GMap_SupplierAddress.Zoom = 0
        End If
    End Sub

    Private Sub EnsureSupplierAddressIsSelected()
        If lb_SupplierAddress.SelectedItems.Count = 0 Then
            Throw New Exception("Proszę, wybierz adres, aby kontynuować.")
        End If
    End Sub


    Private Sub ts_btn_AddressAdd_Click(sender As System.Object, e As System.EventArgs) Handles ts_btn_AddressAdd.Click
        Try
            Dim addressInputDialog As New AddressInputDialog(lb_SupplierAddress.Items.Count = 0)
            If addressInputDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then

                Dim address As Address = addressInputDialog.Address
                Dim description As String = addressInputDialog.Description
                Dim supplierAddress As New SupplierAddress() With {
                    .Address = address,
                    .Description = description,
                    .Supplier = _supplier
                }

                If _supplierAddressList.Any(Function(x) x.Description = description) Then
                    Throw New ArgumentException("Dostawca posiada już adres o takim opisie.")
                End If
                _supplierAddressList.Add(supplierAddress)
                RefreshSupplierAddressListBox(_supplierAddressList)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        End Try
    End Sub

    Private Sub ts_btn_AddressEdit_Click(sender As System.Object, e As System.EventArgs) Handles ts_btn_AddressEdit.Click
        Try
            EnsureSupplierAddressIsSelected()
            Dim selectedSupplierAddress As SupplierAddress = _supplierAddressList.FirstOrDefault(Function(x) x.Description = lb_SupplierAddress.SelectedValue.ToString())
            Dim addressInputDialog As New AddressInputDialog(selectedSupplierAddress)
            If addressInputDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then

                If selectedSupplierAddress.Description <> addressInputDialog.Description AndAlso
                    _supplierAddressList.Any(Function(x) x.Description = addressInputDialog.Description) Then
                    Throw New ArgumentException("Dostawca posiada już adres o takim opisie.")
                End If

                selectedSupplierAddress.Address = addressInputDialog.Address
                selectedSupplierAddress.Description = addressInputDialog.Description

                RefreshSupplierAddressListBox(_supplierAddressList)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        End Try
    End Sub

    Private Sub ts_btn_AddressDelete_Click(sender As System.Object, e As System.EventArgs) Handles ts_btn_AddressDelete.Click
        Try
            EnsureSupplierAddressIsSelected()
            Dim confirmationDialogResult As DialogResult = MessageBox.Show("Czy jesteś pewien?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
            If confirmationDialogResult = Windows.Forms.DialogResult.Yes Then

                Dim selectedSupplierAddress As SupplierAddress = _supplierAddressList.FirstOrDefault(Function(x) x.Description = lb_SupplierAddress.SelectedValue.ToString())
                _supplierAddressList.Remove(selectedSupplierAddress)
                RefreshSupplierAddressListBox(_supplierAddressList)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        End Try
    End Sub
#End Region


#Region "Input validation"

    Private Sub tb_CompanyName_Validating(ByVal sender As Object, ByVal e As CancelEventArgs) Handles tb_CompanyName.Validating
        Dim notNullableInputSpecification As New NotNullableTextInputValidatingSpecification()
        _inputValidator.ValidateTextBox(tb_CompanyName, e, lbl_CompanyNameError, notNullableInputSpecification)
    End Sub

    Private Sub tb_TelephoneNumber_Validating(ByVal sender As Object, ByVal e As CancelEventArgs) Handles tb_TelephoneNumber.Validating
        Dim notNullableInputSpecification As New NotNullableTextInputValidatingSpecification()
        _inputValidator.ValidateTextBox(tb_TelephoneNumber, e, lbl_TelephoneNumberError, notNullableInputSpecification)
    End Sub

    Private Sub tb_EmailAddress_Validating(ByVal sender As Object, ByVal e As CancelEventArgs) Handles tb_EmailAddress.Validating
        Dim emailAddressInputValidatingSpecification As New EmailAddressInputValidatingSpecification()
        _inputValidator.ValidateTextBox(tb_EmailAddress, e, lbl_EmailAddressError, emailAddressInputValidatingSpecification)
    End Sub

    Private Sub tb_CompanyName_Validated(ByVal sender As Object, ByVal e As EventArgs) Handles tb_CompanyName.Validated
        lbl_CompanyNameError.Text = String.Empty
    End Sub

    Private Sub tb_TelephoneNumber_Validated(ByVal sender As Object, ByVal e As EventArgs) Handles tb_TelephoneNumber.Validated
        lbl_TelephoneNumberError.Text = String.Empty
    End Sub

    Private Sub tb_EmailAddressValidated(ByVal sender As Object, ByVal e As EventArgs) Handles tb_EmailAddress.Validated
        lbl_EmailAddressError.Text = String.Empty
    End Sub

#End Region


    Private Sub btn_Accept_Click(sender As System.Object, e As System.EventArgs) Handles btn_Accept.Click
        Try
            If Not ValidateChildren() Then
                Throw New EntityDataInputException("Podane dane są nieprawidłowe." & vbNewLine &
                                                   "Popraw je i spróbuj ponownie.")
            End If

            If lb_SupplierAddress.Items.Count = 0 Then
                Throw New EntityDataInputException("Proszę, dodaj co najmniej jeden adres, aby kontynuować.")
            End If

            Dim confirmationDialogResult As DialogResult = MessageBox.Show("Czy jesteś pewien?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
            If confirmationDialogResult = Windows.Forms.DialogResult.Yes Then
                Supplier.CompanyName = tb_CompanyName.Text.Trim()
                Supplier.EmailAddress = If(String.IsNullOrEmpty(tb_EmailAddress.Text.Trim()), Nothing, tb_EmailAddress.Text.Trim())
                Supplier.FaxNumber = If(String.IsNullOrEmpty(tb_FaxNumber.Text.Trim()), Nothing, tb_FaxNumber.Text.Trim())
                Supplier.TelephoneNumber = tb_TelephoneNumber.Text.Trim()

                'Supplier.SupplierAddresses = _supplierAddressList
                Supplier.SupplierAddresses.Clear()
                For Each sa As SupplierAddress In _supplierAddressList
                    Supplier.SupplierAddresses.Add(sa)
                Next


                DialogResult = Windows.Forms.DialogResult.OK
            End If

        Catch ex As EntityDataInputException
            MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub btn_Cancel_Click(sender As System.Object, e As System.EventArgs) Handles btn_Cancel.Click
        DialogResult = Windows.Forms.DialogResult.No
    End Sub


End Class